import {AxiosRequestConfig, AxiosResponse} from 'axios';
import {ElMessage} from 'element-plus';
import router from '@/router';
import store from '@/store';

let baseURL = import.meta.env.VITE_API_URL;
if (import.meta.env.VITE_NODE_ENV === 'production') {
  baseURL = store.state.href;
}

function startLoading() {
  // console.log('加载请求',ElMessageBox)
}
function endLoading() {
  // console.log('请求关闭')
}

// 请求拦截处理
function requestInterceptor(config: AxiosRequestConfig): AxiosRequestConfig {
  if (config !== undefined) {
    if (config.headers !== undefined) {
      config.headers['Content-type'] = 'application/json;charset=UTF-8';
      config.headers['Access-Control-Max-Age'] = '86000';
      config.headers.token = localStorage.getItem('token') ?? '';
      config.headers.unitToken = localStorage.getItem('unitToken') ?? '';
    }
    config.baseURL = baseURL;
  }

  startLoading();
  return config;
}

// 响应拦截处理
function responseInterceptor(response: AxiosResponse): Promise<AxiosResponse> {
  // 请求后拦截请求数据，进行返回结果业务逻辑操作
  let message = '';
  let msgData = '';
  message = response.data.message;
  switch (response.data.status) {
    case 0:
      return response.data;
    case 1:
      message = response.data.message;
      msgData = response.data.data;
      message = `${message} ${msgData == null || JSON.stringify(msgData) === '[]' ? '' : ',' + msgData}`;
      ElMessage.warning(message);
      return Promise.reject(response);
    case 4:
      ElMessage.warning({
        message: '用户无该权限',
        type: 'warning',
      });
      return Promise.reject(response);
    case 5:
      message = response.data.message;
      for (const key in response.data.data) {
        msgData = response.data.data[key];
        message = `${message} ${msgData == null ? '' : ',' + msgData}`;
      }
      ElMessage.warning({
        message,
        type: 'warning',
      });
      return Promise.reject(response);
    case 999:
      localStorage.removeItem('token');
      localStorage.removeItem('unitToken');
      localStorage.removeItem('userInfo');
      localStorage.removeItem('unit');
      ElMessage.warning({
        message: 'token已过期，请重新登陆，多次登陆不成功请联系管理员',
      });
      router.push({
        path: '/login',
      });
      return Promise.reject(response);
    default:
      ElMessage(response.data.message);
      return Promise.reject(response);
  }
}
// 错误处理
function errHandler(error: any) {
  endLoading();
  return Promise.reject(error);
}

export {requestInterceptor, responseInterceptor, errHandler};
